# app/services/file_service.py
from sqlalchemy.orm import Session
from app.models.file_model import File
import traceback

class FileService:
    @staticmethod
    def save_file(db: Session, biz_type: str, biz_id: int, filename: str, content: bytes):
        try:
            record = File(
                biz_type=biz_type,
                biz_id=biz_id,
                url=f"/api/files/{biz_id}/{biz_type}",  # 临时，后面会刷新
                blob_data=content,
            )
            db.add(record)
            db.commit()
            db.refresh(record)
            # 生成真实 URL
            record.url = f"/api/files/{record.id}"
            db.commit()
            return 201, "上传成功", record
        except Exception as e:
            db.rollback()
            traceback.print_exc()
            return 500, f"上传失败: {e}", None

    @staticmethod
    def get_file(db: Session, file_id: int):
        return db.query(File).filter(File.id == file_id).first()